package com.chx.service.Impl;

import com.chx.constant.MessageConstant;
import com.chx.constant.StatusConstant;
import com.chx.dto.CategoriesDto;
import com.chx.dto.CategoryPageQueryDto;
import com.chx.entity.Categories;
import com.chx.exception.DeletionNotAllowedException;
import com.chx.mapper.CategoryMapper;
import com.chx.result.PageResult;
import com.chx.service.CategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @Author cp-月入过万
 * @Date 2025/5/30
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Categories> getAllCategories() {
        return categoryMapper.getAllCategories();
    }

    @Override
    public void save(CategoriesDto categoriesDto) {
        Categories categories = new Categories();
        BeanUtils.copyProperties(categoriesDto, categories);
        if (Objects.equals(categories.getParentId(), StatusConstant.ROLE_ADMIN))
            categories.setParentId(StatusConstant.SUPER_ADMIN);
        categoryMapper.insert(categories);
    }

    @Override
    public void update(CategoriesDto categoriesDto) {
        Categories categories = new Categories();
        BeanUtils.copyProperties(categoriesDto, categories);
        if (Objects.equals(categories.getParentId(), StatusConstant.ROLE_ADMIN))
            categories.setParentId(StatusConstant.SUPER_ADMIN);
        categoryMapper.update(categories);
    }

    @Override
    public void delete(Long id) {
        if(categoryMapper.getCategoryById(id)>0)
            throw new DeletionNotAllowedException(MessageConstant.DELETE_CATEGORY);
        if(categoryMapper.getProductById(id)>0)
            throw new DeletionNotAllowedException(MessageConstant.DELETE_HAS_CATEGORY);
        categoryMapper.delete(id);
    }

    @Override
    public Categories getById(Long id) {
        return categoryMapper.getById(id);
    }

    @Override
    public PageResult page(CategoryPageQueryDto categoryPageQueryDto) {
        PageHelper.startPage(categoryPageQueryDto.getPage(), categoryPageQueryDto.getPageSize());
        Page<Categories> page = categoryMapper.page(categoryPageQueryDto);
        long total = page.getTotal();
        List<Categories> records = page.getResult();
        return new PageResult(total, records);
    }
}
